package quick.start.core.connect.request;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonRequestWrapper extends RequestWrapper {

    private String jsonEntity;

    @Override
    public HttpUriRequest genRequest() {
        HttpPost request = new HttpPost(HttpParams.appendToUrl(params, url));

        if (null != jsonEntity) {
            StringEntity s = null;
            try {
                s = new StringEntity(jsonEntity, HTTP.UTF_8);
                s.setContentType("application/json");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            request.setEntity(s);
        }
        return request;
    }

    public static class Builder extends DefaultRequestBuilder {
        private String jsonEntity;

        public Builder jsonEntity(String jsonEntity) {
            this.jsonEntity = jsonEntity;
            return JsonRequestWrapper.Builder.this;
        }

        @Override
        public JsonRequestWrapper build() {
        	JsonRequestWrapper reqWrapper = new JsonRequestWrapper();
            preBuild(reqWrapper);
            reqWrapper.jsonEntity = jsonEntity;
            return reqWrapper;
        }
    }

    @Override
    public String dump() {
        return super.dump() + "\n json entity: " + jsonEntity;
    }
}
